package pers.cz.annotation;

import org.reflections.Reflections;
import org.springframework.context.annotation.ImportSelector;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.annotation.MergedAnnotation;
import org.springframework.core.annotation.MergedAnnotations;
import org.springframework.core.type.AnnotationMetadata;
import pers.cz.node.Node;
import pers.cz.node.NodeEnum;
import pers.cz.utils.AnnoManageUtil;
import pers.cz.utils.DynamicEnumUtil;
import pers.cz.utils.LogUtils;

import java.util.List;
import java.util.Set;

/**
 * @program: jef-flow-spring-boot-starter
 * @description:
 * @author: Cheng Zhi
 * @create: 2023-02-08 13:52
 **/
public class JefFlowSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {

        // 处理注解
        AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(EnableJefFlow.class.getName()));
        String[] basePackages = annotationAttributes.getStringArray("basePackages");
        for (String basePackage : basePackages) {

            List<Class<?>> packageAnnos = AnnoManageUtil.getPackageAnno(basePackage, AutoRegister.class);
            for (Class<?> c : packageAnnos) {
                init(basePackage, c);
            }
            /*// 扫描指定包下的类
            Reflections ref = new Reflections(basePackage);
            // 获取扫描到的标记注解的集合
            Set<Class<?>> set = ref.getTypesAnnotatedWith(AutoRegister.class);
            System.out.println("--------start-------------");
            for (Class<?> c : set) {
                init(c);
            }*/
        }
        return new String[] {"pers.cz.starter.JefFlowAutoConfiguration"};
    }

    public void init(String basePackage, Class<?> clazz) {
        String className = clazz.getName();
        // 获取到的类全名需要去掉包名
        className = className.replaceAll(basePackage + ".","");
        // 默认截取去掉后四位的剩余部分
        String nodeName = className.substring(0,className.length()-4);
        LogUtils.debug(nodeName + "注册成功！！！");
        // 进行注册
        registerEnum(nodeName, clazz);
    }
    public void registerEnum(String nodeName, Class nodeClass) {
        // 默认自动添加枚举
        addNodeEnum(nodeName.toUpperCase(), nodeName.toLowerCase(), nodeClass);
    }


    /**
     * 添加枚举
     * @param enumName 枚举名
     * @param code 枚举项1
     * @param nodeClass 枚举项2
     */
    private void addNodeEnum(String enumName, String code, Class<? extends Node> nodeClass) {
        DynamicEnumUtil.addEnum(NodeEnum.class, enumName, new Class<?>[]{String.class, Class.class}, new Object[]{code, nodeClass});
    }
}
